import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:largefriends/config/lf_config.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_bool_entity.dart';
import 'package:largefriends/entity/entities/lf_user_entity.dart';
import 'package:largefriends/net/error_handle.dart';
import 'package:largefriends/net/lf_api_url.dart';
import 'package:largefriends/net/lf_dio_util.dart';
import 'package:largefriends/pages/lf_login/recaptcha_sheet.dart';
import 'package:largefriends/res/lf_color.dart';
import 'package:largefriends/res/lf_double_ext.dart';
import 'package:largefriends/res/lf_string_ext.dart';
import 'package:largefriends/res/lf_text_style.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/utils/lf_dialog_utils.dart';
import 'package:largefriends/utils/lf_keyboard.dart';
import 'package:pinput/pinput.dart';

import '../../res/lf_fonts.dart';
import '../../res/strings/lf_strings.dart';
import '../../widgets/dialog_action_tip.dart';
import '../../widgets/lf_button.dart';
import '../lf_feedback/lf_feedback_logic.dart';

toLoginPage() {
  Get.toNamed(LFRoute.pathLogin);
}

class LfLoginLogic extends GetxController {
  final FocusNode emailFocusNode = FocusNode();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();
  RxBool emailFocused = false.obs;
  LfAuthService authService = Get.find<LfAuthService>();

  RxString email = ''.obs;
  RxString password = ''.obs;

  bool get buttonEnable =>
      email.value.isEmail &&
      password.isNotEmpty &&
      password.trim().length >= minPassword;

  login({String? reCaptchaKey, String? verifyKey, String? verifyCode}) {
    closeSoftKeyboard();
    Map<String, String> requestParam = {
      'email': email.value.trim(),
      'password': password.value.trim(),
    };

    if (reCaptchaKey.isNullOrEmpty == false) {
      requestParam['reCaptchaKey'] = reCaptchaKey ?? "";
    } else if (verifyKey != null &&
        verifyCode != null &&
        verifyCode.isNotEmpty) {
      requestParam['twoFactorKey'] = verifyKey;
      requestParam['twoFactorCode'] = verifyCode;
    }
    if (reCaptchaKey.isNullOrEmpty) {
      showLoading();
    }
    LfDio()
        .post<LfUserEntity>(
      url: apiSignIn,
      params: requestParam,
    )
        .then(
      (value) {
        hideLoading();
        authService.setUserEntity(value);
        authService.updateLastLoginInfo(email.value.trim());
        Get.offAllNamed(LFRoute.pathHome);
      },
      onError: (error) {
        hideLoading();
        if (error is NetError) {
          if (error.code == 30001055) {
            //不用处理,因为token的地方拦截了
          } else if (error.code == 30001051) {
            showRecaptcha(Get.context!, error.msg, (value) {
              _postRecaptcha(value);
            });
          } else if (error.code == 30001021) {
            _showDisableSheet();
          } else if (error.code == 30001052) {
            _showFactorSheet(email: email.value.trim(), twoFactor: error.msg);
            return;
          } else {
            showSnackBar(error.msg);
          }
        }
      },
    );
  }

  _postRecaptcha(String recaptcha) {
    showLoading();
    LfDio().post<LfBoolEntity>(
        url: apiRecaptchaVerify,
        params: {'reCaptchaKey': recaptcha}).then((value) {
      login(reCaptchaKey: recaptcha);
    }, onError: (error) {
      hideLoading();
      if (error is NetError) {
        showSnackBar(error.msg);
      }
    });
  }

  _showDisableSheet() {
    showActionTips(
        tips: strChangeProfileOnlineTip.tr,
        actionButtonTip: strYes.tr,
        action: () {
          _enableAccount();
        },
        dismissible: false);
  }

  _enableAccount() {
    showLoading();
    var params = {'email': email.value, 'password': password.value.trim()};
    LfDio.instance
        .post<LfUserEntity>(
      url: apiEnableAccount,
      params: params,
    )
        .then((value) {
      hideLoading();
      authService.setUserEntity(value);
      authService.updateLastLoginInfo(email.value.trim());
      Get.offAllNamed(LFRoute.pathHome);
    }, onError: (error) {
      hideLoading();
      if (error is NetError) {
        showSnackBar(error.msg);
      }
    });
  }

  _showFactorSheet({required String email, required String twoFactor}) async {
    RxString pinCode = ''.obs;
    final pinTheme = PinTheme(
        width: 35.r,
        height: 35.r,
        textStyle: lfTextStyle(sp: 15.sp),
        decoration: BoxDecoration(
          color: color50F2A7BE,
          borderRadius: BorderRadius.all(Radius.circular(5.r)),
        ));

    await Get.dialog(AlertDialog(
      titlePadding: EdgeInsets.zero,
      clipBehavior: Clip.antiAlias,
      title: Container(
        padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
        alignment: Alignment.center,
        child: Text(
          strEnterSecurityCode.tr,
          textAlign: TextAlign.center,
          style: lfTextStyle(
            sp: 18.sp,
            fontFamily: fontMedium,
          ),
        ),
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            height: 10.h,
          ),
          Padding(
            padding: EdgeInsets.symmetric(
              horizontal: 10.w,
            ),
            child: Text(
              strCheckEmailTip.tr,
              style: lfTextStyle(
                sp: 16.sp,
                fontFamily: fontRegular,
              ),
              textAlign: TextAlign.center,
            ),
          ),
          5.h.sbh,
          Text(
            email,
            style: lfTextStyle(
              sp: 16.sp,
              fontFamily: fontMedium,
            ),
            textAlign: TextAlign.center,
          ),
          15.h.sbh,
          Pinput(
            length: 6,
            defaultPinTheme: pinTheme,
            focusedPinTheme: pinTheme,
            submittedPinTheme: pinTheme,
            onCompleted: (pin) {
              pinCode.value = pin;
            },
            onChanged: (pin) {
              pinCode.value = pin;
            },
          ),
          15.h.sbh,
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Obx(
              () => LfButton(
                text: strContinue.tr,
                enabled:
                    pinCode.value.isNotEmpty && (pinCode.value.length == 6),
                onPress: () {
                  hideDialog();
                  login(verifyKey: twoFactor, verifyCode: pinCode.value);
                },
              ),
            ),
          ),
          15.h.sbh,
          InkWell(
            onTap: () {
              hideDialog();
              toFeedback(type: FeedbackType.account);
            },
            child: Text(
              'Trouble accessing the email?',
              textAlign: TextAlign.center,
              style: lfTextStyle(
                  sp: 16.sp,
                  fontFamily: fontRegular,
                  decoration: TextDecoration.underline),
            ),
          ),
          10.h.sbh,
        ],
      ),
      contentPadding: EdgeInsets.zero,
      actionsPadding: EdgeInsets.zero,
      insetPadding: EdgeInsets.symmetric(horizontal: 10.w),
    ));
  }

  @override
  void onInit() {
    super.onInit();
  }
}
